/**
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xbxkj.mix.controller;

import cn.hutool.db.nosql.redis.RedisDS;
import com.xbxkj.mix.config.WebScoketService;
import com.xbxkj.mix.service.UserService;
import com.xbxkj.mix.util.IpUtil;
import com.xbxkj.mix.util.result.ApiController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import redis.clients.jedis.Jedis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

/**
 * @author Zhang
 * @date 2018-11-08
 */
@Slf4j
public abstract class BaseController extends ApiController {
    @Autowired
    protected    UserService userService;

    @Value("${redisDS.group}")
    String redisGroup="";

    /**
     * 获取jedis
     * @return
     */
    protected  Jedis jedis( ){
        return  new RedisDS(redisGroup).getJedis();
    }

    /**
     * 获取缓存
     * @return
     */
    protected <T> T  getCache(String key, Class<T> clazz){
        return  (T) byteArrToObject(jedis().get(key.getBytes()));
    }

    /**
     * 缓存存储
     * @return
     */
    protected void putCache(String key, byte[] value ){
          jedis().set(key.getBytes(),value);
          jedis().close();
    }

    /**
     * 缓存存储  过期时间秒
     * @return
     */
    protected void putCache(String key  , byte[] value , int time){
        byte[] k=key.getBytes();
        jedis().set(k,value);
        jedis().expire(k,time);
        jedis().close();
    }





    /**
     * webSocket 单点发送消息
     * @return
     */
    protected  void sendMsg(String token,String msg ){
        log.debug("发送给token是{}的用户的消息为：{}",token,msg);
        try {
            WebScoketService.webSocketSet.get(token).sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("发送给ID是{}的用户的消息为：{}的时候，发送失败",token,msg);
        } catch (NullPointerException e) {
            log.error("发送给ID是{}的用户的消息为：{}的时候，用户不在线",token,msg);
        }
    }

    /**
     * webSocket 群发送消息
     * @return
     */
    protected  void sendMsg( String msg ){
        log.debug("群发的消息为：{}",msg);
        try {
            //群发消息
            for (String item :  WebScoketService.webSocketSet.keySet()) {
                try {
                    WebScoketService.webSocketSet.get(item).sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("群发的消息为：{}的时候，发送失败",msg);
        }
    }


    /**
     * 获取当前请求
     *
     * @return request
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    protected HttpSession getSession() {
        return getRequest().getSession();
    }
    /**
     * 获取当前请求
     *
     * @return response
     */
    protected HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }
    /**
     * 方法名称: renderText<br>
     * 描述：返回普通文本浏览器
     */
    protected void renderText(String text){
        render(text, MediaType.TEXT_HTML_VALUE);
    }

    /**
     * 方法名称: renderJson<br>
     * 描述：返回JSON格式数据
     */
    protected void renderJson(String text){
        render(text,  MediaType.APPLICATION_JSON_UTF8_VALUE );
    }

    /**
     * 获取请求用户的IP地址
     */
    protected String getIpAddr( ) {
        return IpUtil.getRequestIp(getRequest());
    }
    /**
     * 获取cookie
     * @param cookieName
     * @return
     */
    protected String getCookie(String cookieName) {
        Cookie[] cookies = getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }

        return null;
    }

    /**
     * 设置 cookie
     *
     * @param cookieName
     * @param value
     * @param age
     */
    protected void setCookie(String cookieName, String value, int age) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setMaxAge(age);
        getResponse().addCookie(cookie);
    }


    private void render(String text, String contentType){
        HttpServletResponse response;
        try{

            response = getResponse();
                response.setContentType(contentType);

            response.getWriter().write(text);
            response.getWriter().flush();
        }
        catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * 对象转数组
     * @param obj
     * @return
     */
    protected static byte[] objectToByteArray (Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 数组转对象
     * @param bytes
     * @return
     */
    protected static Object byteArrToObject (byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
            ObjectInputStream ois = new ObjectInputStream (bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }
}